#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 将需刷新的url填写到 /data/urls.ini 文件中

import urllib2
import json
import sys
import datetime
import re
import time


reload(sys)
sys.setdefaultencoding('utf-8')


def getLocalTime(args):
    '''
    年，月，日，时，分，秒，周
    '''
    format_dict = {
        '年': '%Y',
        '月': '%m',
        '日': '%d',
        '时': '%H',
        '分': '%M',
        '秒': '%S',
        '周': '%w',
    }
    format_string = args
    for s in format_dict:
        reobj = re.compile(s)
        format_string = reobj.sub(format_dict[s], format_string)
    return datetime.datetime.now().strftime(format_string)


def httpRequest(url, data=None, header=None, req_timeout=30):
    try:
        if header is None and data is None:
            req = urllib2.Request(url)
        else:
            req = urllib2.Request(url, data, headers=header)
        response = urllib2.urlopen(req, None, req_timeout)
        response_info = json.loads(response.readlines()[0])
        return [str(response.getcode()), response_info]
    except urllib2.HTTPError:
        print('http 访问出错，退出程序')
        sys.exit(1)


token = "94675ee22e5f3bbfc0c9d5693c4eb5b6"
host_url = "https://api.qingcdn.com/v2/cache/refresh?token=%s" % token
url_file = "/data/urls.ini"
urls = []
status_code_list = {
    "404": "您输入的 URL 错误",
    "401": "鉴权错误，您的 token 可能是不对的",
    "400": "请求参数有误",
    "200": "刷新成功",
}


try:
    with open(url_file, 'rw') as f:
        for line in f:
            urls.append(line.strip('\n'))
        if len(urls) == 0:
            print("%s 为空" % url_file)
            sys.exit(1)
except IOError:
    print("读取文件 %s 错误" % url_file)
    sys.exit(1)

# 刷新缓存
data = json.dumps({"urls": urls, "type": "url"})
header = {"Content-Type": "application/json"}
req_timeout = 30
status_code, response_info = httpRequest(
    host_url, data=data, header=header, req_timeout=req_timeout)
print("状态码:%s\n结果信息:%s" % (status_code, status_code_list[status_code]))
if response_info['data']['count'] != len(urls):
    print('以下url刷新失败:%s' % '\n'.join(response_info['data']['err_urls']))

# 查询缓存刷新结果
task_id = response_info['data']['task_id']
page_number = 100
start_time = getLocalTime('年-月-日')
end_time = getLocalTime('年-月-日')
check_host_url = "https://api.qingcdn.com/v2/cache/refresh?\
token=%s&task_id=%s" % (token, task_id)
time.sleep(3)
response_check_code, response_check_info = httpRequest(
    check_host_url, req_timeout=req_timeout)
flush_status = response_check_info['data']['list']
for line in flush_status:
    print("%s 刷新状态:%s" % (line[u'url'], line[u'status']))
